<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="套餐名称" prop="Name">
        <el-input
          v-model="queryParams.Name"
          placeholder="请输入套餐名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="套餐状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:goods:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:goods:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:goods:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="packageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="套餐名称" prop="name"/>
      <el-table-column label="原价" prop="marketPrice">
        <template slot-scope="scope">
          <span style="text-decoration: line-through">{{scope.row.marketPrice}}</span>
        </template>
      </el-table-column>
      <el-table-column label="现价" prop="price">
        <template slot-scope="scope">
          <span>{{scope.row.price}}</span>
        </template>
      </el-table-column>
      <el-table-column label="代理商价格" prop="proxyPrice"/>
      <el-table-column label="套餐状态" align="center">
        <template slot-scope="scope">
          <span style="color:#409EFF;" v-if="scope.row.status == 0">正常</span>
          <span style="color:#F56C6C;" v-if="scope.row.status == 1">停用</span>
        </template>
      </el-table-column>
      <el-table-column label="套餐发送数量" prop="voideCount" align="center"/>
      <el-table-column label="赠送次数" prop="voideGive" align="center"/>
      <el-table-column label="套餐说明" prop="remark" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.packageId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:goods:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:goods:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改套餐配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入套餐名称"/>
        </el-form-item>
        <el-form-item label="现价" prop="price">
          <el-input v-model="form.price" placeholder="请输入套餐现价"/>
        </el-form-item>
        <el-form-item label="套餐原价" prop="marketPrice">
          <el-input v-model="form.marketPrice" placeholder="请输入套餐原价"/>
        </el-form-item>
        <el-form-item label="代理商价格" prop="proxyPrice">
          <el-input v-model="form.proxyPrice" placeholder="请输入代理商的价格"/>
        </el-form-item>
        <el-form-item label="套餐发送量" prop="voideCount">
          <el-input v-model.number="form.voideCount" controls-position="right" placeholder="请输入要发送的套餐数量"/>
        </el-form-item>
        <el-form-item label="赠送次数" prop="voideGive">
          <el-input v-model="form.voideGive" placeholder="请输入赠送次数"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="套餐说明">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :autosize="{ minRows: 3, maxRows: 6}"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRole, dataScope, changePackageStatus } from '@/api/system/role'
import { treeselect as menuTreeselect, roleMenuTreeselect } from '@/api/system/menu'
import { treeselect as deptTreeselect, roleDeptTreeselect } from '@/api/system/dept'
// import { downLoadExcel } from "@/utils/download";
import { packagelist, addpackage, editpackage, delpackage, getpackage } from '@/api/package/package'

export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 套餐列表格数据
      packageList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 数据范围选项
      dataScopeOptions: [
        {
          value: '1',
          label: '全部数据权限'
        },
        {
          value: '2',
          label: '自定数据权限'
        },
        {
          value: '3',
          label: '本部门数据权限'
        },
        {
          value: '4',
          label: '本部门及以下数据权限'
        },
        {
          value: '5',
          label: '仅本人数据权限'
        }
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '套餐名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在6-10个字符之间', trigger: 'change' }
        ],
        marketPrice: [
          { required: true, message: '套餐原价不能为空', trigger: 'blur' },
          {
            pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
            message: '请输入正确的套餐原价:整数或者保留两位小数',
            trigger: 'blur'
          }
        ],

        voideCount: [
          { required: true, message: '套餐发送量不能为空', trigger: 'blur' },
          { type: 'number', message: '数量必须为整型数字值', trigger: 'change' }
        ],
        proxyPrice: [
          { required: true, message: '代理商价格不能为空', trigger: 'blur' },
          {
            pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
            message: '请输入正确的代理商价格:整数或者保留两位小数',
            trigger: 'blur'
          }
        ],
        price: [
          { required: true, message: '现价不能为空', trigger: 'blur' },
          {
            pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
            message: '请输入正确的现价:整数或者保留两位小数',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.data
    })
  },
  methods: {
    /** 查询套餐列表 */
    getList() {
      this.loading = true
      packagelist(this.queryParams).then((response) => {
        this.packageList = response.rows
        this.total = response.total
        this.loading = false
      })
      // console.log(typeof(this.packageList.marketPrice));
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        status:0
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // this.getMenuTreeselect();
      this.open = true
      this.title = '添加套餐';

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const packageIds = row.id || this.ids
      getpackage(packageIds).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改套餐'
      })
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset()
      getRole(row.packageId).then((response) => {
        this.form = response.data
        this.openDataScope = true
        this.$nextTick(() => {
          roleDeptTreeselect.then((res) => {
            this.$refs.dept.setCheckedKeys(res.data.checkedKeys)
          })
        })
        this.title = '分配数据权限'
      })
    },
    /** 分配用户操作 */
    handleAuthUser: function(row) {
      const roleId = row.roleId
      this.$router.push('/system/role-auth/user/' + roleId)
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            editpackage(this.form).then((response) => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addpackage(this.form).then((response) => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function() {
      if (this.form.packageId != undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys()
        dataScope(this.form).then((response) => {
          this.msgSuccess('修改成功')
          this.openDataScope = false
          this.getList()
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const packageIds = row.id || this.ids
      this.$confirm(
        '是否确认删除套餐编号为"' + packageIds + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delpackage(packageIds)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    }
  }
}
</script>
